/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import TauTable from '@/components/TauTable';
import { Button, Dialog, Form } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, column } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';


const FromItem = Form.Item;

const RelatedCustomers = ({ modal, username, onCancel }) => {
  const { managersStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal?.show === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [replated] = useState(() => observable({}));
  const [currentData, setCurrentData] = useState([]);

  useEffect(() => { if (modal.close?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    store.search_relate = {
      receiver: username,
    };
    (async () => {
      const res = await store.getManagersInfo({
        search: {
          receiver: username,
          receiving: true,
        },
        pg: {
          page: 0,
          size: 99,
        },
      });
      setCurrentData(res);
    })();
  }, []);

  if (!replated) return <></>;

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(replated, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={replated}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`当前有效关联客户`} />
      <TauTable
        primaryKey="id"
        tableLayout="fixed"
        dataSource={currentData}
        hidePagination
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx_relate(i) },
          column('targetUserName', {}),
          column('targetUserUsername', {}),
          column('crDate', {}),
        ]}
      />
      <TitleGrid title={t`历史关联客户`} />
      <TauTable
        primaryKey="id"
        tableLayout="fixed"
        currentPage={store.pg_relate.page}
        pageSize={store.pg_relate.size}
        total={store.relate_total}
        onFetch={(pg) => { store.pg_relate = pg; }}
        loading={store.relate_loading}
        dataSource={toJS(store.relate_data)}
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx_relate(i) },
          column('targetUserName', {}),
          column('targetUserUsername', {}),
          column('crDate', {}),
        ]}
      />
      <DrawerFooter>
        <FromItem>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(RelatedCustomers);
